package com.oweight.sagacious.auth.server.interfaces.controller;

import com.oweight.sagacious.api.model.msg.Message;
import com.oweight.sagacious.auth.server.domain.service.IClientManager;
import com.oweight.sagacious.auth.server.infrastructure.util.user.JwtAuthenticationRequest;
import com.oweight.sagacious.auth.server.infrastructure.util.user.WeChatLoginForm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * JWT
 *
 * @author 周广明
 * @version v1 2019/10/21 16:52
 */
@Slf4j
@RestController
@RequestMapping("jwt")
public class AuthController {

    @Value("${jwt.token-header}")
    private String tokenHeader;

    @Autowired
    private IClientManager authService;

    /**
     * 获取Token
     *
     * @param authenticationRequest
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "token", method = RequestMethod.POST)
    public Message createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest) throws Exception {
        log.info(authenticationRequest.getUsername() + " require logging...");
        final String token = authService.login(authenticationRequest);
        return new Message().ok("获取Token成功!").data(token);
    }

    /**
     * 微信登录获取Token
     *
     * @param form
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/token/wx", method = RequestMethod.POST)
    public Message createAuthenticationTokenByWeChat(@RequestBody WeChatLoginForm form) throws Exception {
        log.info(form.getAppId() + " require logging...");
        final String token = authService.login2(form);
        return new Message().ok("获取Token成功!").data(token);
    }

    /**
     * 刷新Token
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "refresh", method = RequestMethod.GET)
    public Message refreshAndGetAuthenticationToken(HttpServletRequest request) throws Exception {
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        return new Message().ok("刷新Token成功!").data(refreshedToken);
    }

    /**
     * 校验Token
     *
     * @param token
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "verify", method = RequestMethod.GET)
    public Message verify(String token) throws Exception {
        try {
            authService.validate(token);
        } catch (Exception e) {
            log.error("Token校验失败！", e);
            return new Message().error("校验失败！").data(false);
        }
        return new Message().ok("校验成功！").data(true);
    }
}
